package com.dmsdbj.itoo.graduate.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dmsdbj.itoo.authorizationManagement.entity.AllusersEntity;
import com.dmsdbj.itoo.authorizationManagement.facade.AllusersFacade;
import com.dmsdbj.itoo.authorizationManagement.facade.RoleFacade;
import com.dmsdbj.itoo.authorizationManagement.facade.UserRoleFacade;
import com.dmsdbj.itoo.graduate.dao.PersonalInfoDao;
import com.dmsdbj.itoo.graduate.entity.DictionaryEntity;
import com.dmsdbj.itoo.graduate.entity.PersonalInfoEntity;
import com.dmsdbj.itoo.graduate.entity.ext.*;
import com.dmsdbj.itoo.graduate.mybatisexample.PersonalInfoCriteria;
import com.dmsdbj.itoo.graduate.mybatisexample.PersonalInfoExample;
import com.dmsdbj.itoo.graduate.service.*;
import com.dmsdbj.itoo.graduate.tool.ResultEmptyUtil;
import com.dmsdbj.itoo.tool.base.dao.BaseDao;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServiceImpl;
import com.dmsdbj.itoo.tool.uuid.BaseUuidUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

//import java.text.SimpleDateFormat;

/**
 * @author : 徐玲博
 *         create : 2017-11-21 21:47:13
 *         DESCRIPTION 个人信息ServiceImpl
 */
@Service("personalInfoService")
public class PersonalInfoServiceImpl extends BaseServiceImpl<PersonalInfoEntity, PersonalInfoExample> implements PersonalInfoService {


    //注入personalInfoDao
    @Autowired
    private PersonalInfoDao personalInfoDao;

    //注入字典表Service
    @Autowired
    private DictionaryService dictionaryService;

    //注入薪资表Service
    @Autowired
    private SalaryService salaryService;

    //注入人员公司关系表service
    @Autowired
    private PersonCompanyRelationService personCompanyRelationService;

    //注入人员技能关系表Service
    @Autowired
    private PersonSkillRelationService personSkillRelationService;

    //注入homeInfoService
    @Autowired
    private HomeInfoService homeInfoService;
    //注入pictureService
    @Autowired
    private PictureService pictureService;

    //注入权限AllusersFacade ;
    @Reference
    private AllusersFacade allusersFacade;
    //注入权限UserRoleFacade
    @Reference
    private UserRoleFacade userRoleFacade;
    //注入权限RoleFacade
    @Reference
    private RoleFacade roleFacade;

    private static final String IS_GRADUATE = "是";
    private static final String IS_NOT_GRADUATE = "否";

    /**
     * 根据id 查询个人信息-徐玲博-2018-1-21 12:15:07
     *
     * @param id 个人id
     * @return 个人信息
     */
    @Override
    public PersonalInfoEntity findByUserId(String id) {

        PersonalInfoEntity personalInfoEntity = personalInfoDao.findById(id);

        if (personalInfoEntity == null) {
            return null;
        }
        //年级返回字符串
//        String grade = personalInfoEntity.getGrade();
//        String gradeName = dictionaryService.findDictionaryNameById(grade);
//        personalInfoEntity.setGrade(gradeName);

//        紧急联系人关系
//        String emergRelation = dictionaryService.findDictionaryNameById(personalInfoEntity.getEmergRelation());
//        personalInfoEntity.setEmergRelation(emergRelation);
        return personalInfoEntity;
    }

    /**
     * 根据id 查询个人信息-包括图像-徐玲博-2018-2-6 15:35:22
     *
     * @param id 用户id
     * @return 用户信息
     */
    @Override
    public PersonInfoModel selectByPersonId(String id) {
        PersonalInfoEntity personalInfoEntity = findByUserId(id);
        PersonInfoModel personInfoModel = new PersonInfoModel();
        //获取个人图片
        List<String> pictureUrl = pictureService.selectPictureById(id);
        if (!CollectionUtils.isEmpty(pictureUrl)) {
            personInfoModel.setPictureUrl(pictureUrl.get(0));
        }

        //紧急联系人关系
        String emergRelationName = dictionaryService.findDictionaryNameById(personalInfoEntity.getEmergRelation());
        personInfoModel.setEmergRelationName(emergRelationName);
        BeanUtils.copyProperties(personalInfoEntity, personInfoModel);

        //年级返回字符串
        String grade = personalInfoEntity.getGrade();
        String gradeName = dictionaryService.findDictionaryNameById(grade);
        personInfoModel.setGradeName(gradeName);
        return personInfoModel;
    }

    /*
      转换时间戳为Date类型-徐玲博-2018-1-21 21:40:21

      @return date类型日期
     */
//    @Override
//    public Date covertTimeStampToDate(Date timeStamp) {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        String bir = sdf.format(timeStamp);
//
//        Date data = java.sql.Date.valueOf(bir);
//        return data;
//    }

    /**
     * 让BaseServiceImpl获取到Dao
     *
     * @return BaseDao<PersonalInfoEntity,PersonalInfoExample>
     */
    @Override
    public BaseDao<PersonalInfoEntity, PersonalInfoExample> getRealDao() {
        return this.personalInfoDao;
    }


    /**
     * 根据登录ID查询用户信息-徐玲博-2017-11-19 11:32:48
     *
     * @param loginId 登录ID
     * @return 个人信息实体
     */
    @Override
    public PersonalInfoEntity selectPersonByLoginId(String loginId) {
        return personalInfoDao.selectPersonByLoginId(loginId);
    }


    /**
     * 毕业生-根据用户Id-删除个人信息-徐玲博-2017-11-19 11:43:50
     * 删除该用户，所有相关的信息，例如家庭、公司、薪资、学历等都将被删除
     *
     * @param personId 用户Id
     * @param operator 操作人
     * @return 受影响行
     * 2017-11-28 14:33:13
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePersonInfo(String personId, String operator) {
        if (StringUtils.isAnyEmpty(personId, operator)) {
            return false;
        }
        //1.1、根据人员id查询人员公司关系id的list
        List<String> personCompanyRelationIds = personCompanyRelationService.selectPersonCompanyRelationIdsByPersonId(personId);
        //1.2、根据人员公司关系list删除t_salary表记录
        int num = salaryService.deleteSalaryInfoByRelationIds(personCompanyRelationIds, operator);
        if (num <= 0) {
            return false;
        }

        //2、根据人员id删除人员公司关系记录
        boolean isDeletePersonCompanyRelation = personCompanyRelationService.deletePersonCompanyRelationByPersonId(personId, operator);
        if (!isDeletePersonCompanyRelation) {
            return false;
        }

        //3、根据人员id删除人员技术点关系记录
        boolean isDeletePersonSkillRelation = personSkillRelationService.deletePersonSkillRelationByPersonId(personId, operator);
        if (!isDeletePersonSkillRelation) {
            return false;
        }

        //4、根据人员id删除t_home_info家乡记录
        int deleteHomeInfoNum = homeInfoService.deleteHomeInfo(personId, operator);
        if (deleteHomeInfoNum <= 0) {
            return false;
        }

        //5、根据人员id删除t_education教育记录
        //TODO:yyl  等接口

        //说明：6/7/8、步一期不删除。二期重新考虑。
        //6、根据人员id删除t_land_scape景观记录
        //7、根据人员id删除t_commercial_oppotunity商业机会记录
        //8、根据人员id删除t_local_product特产记录

        //9、根据人员id删除t_personalInfo人员记录
        boolean isDeletePerson = false;
        int deletePersonNum = this.deleteById(personId, operator);
        if (deletePersonNum > 0) {
            isDeletePerson = true;
        }
        return isDeletePerson;
    }

    /**
     * 根据毕业生姓名查询个人信息-徐玲博-2017-11-30 17:14:23
     *
     * @param name 毕业生姓名
     * @return list列表
     */
    @Override
    public List<PersonalInfoEntity> selectPersonByName(String name) {
        PersonalInfoExample personalInfoExample = new PersonalInfoExample();
        PersonalInfoCriteria personalInfoCriteria = personalInfoExample.createCriteria();
        personalInfoCriteria
                .andNameEqualTo(name)
                .andIsDeleteEqualTo((byte) 0);
        return personalInfoDao.selectByExample(personalInfoExample);
    }

    /**
     * 根据期数查询毕业生 -李爽-2017-12-7 17:36:38
     *
     * @param grade 期数
     * @return 毕业生list
     */
    @Override
    public List<PersonalInfoEntity> selectPersonByGrade(String grade) {
        if (StringUtils.isEmpty(grade)) {
            return null;
        }
        String gradeId = dictionaryService.findDictionaryIdByName(grade);
        if (StringUtils.isEmpty(gradeId)) {
            return null;
        }
        PersonalInfoExample example = new PersonalInfoExample();
        example.createCriteria()
                .andGradeEqualTo(gradeId)
                .andIsDeleteEqualTo((byte) 0);
        List<PersonalInfoEntity> list = personalInfoDao.selectByExample(example);
        return ResultEmptyUtil.getReturnValue(list);
    }

    /**
     * 组合查询+模糊查询+分页查询 毕业生信息查询-徐玲博-2018-1-2 11:13:16
     *
     * @param name        毕业生姓名
     * @param company     最新公司信息
     * @param grade       期数
     * @param education   学历
     * @param salaryRange 薪资范围
     * @param page        页码
     * @param pageSize    页大小
     * @return 毕业生信息list
     */
    @Override
    public PageInfo<PersonManageModel> selectPersonByCombination(String name, String company, String grade, String education, String salaryRange, int page, int pageSize) {

//        PageHelper.startPage(page, pageSize);


        //and最新薪资End
        //TODO 问题：薪资范围有大于小于1个值，两个范围值
        List<String> stringList = salaryRangeSegment(salaryRange);
        String salaryStart = stringList.get(0);//范围开始
        String salaryEnd = stringList.get(1);//范围结束

        //and期数
        String gradeId = "";
        if (!"".equals(grade) || !StringUtils.isEmpty(grade)) {
            gradeId = dictionaryService.findDictionaryIdByName(grade);//去字典表中查询期数，取得字典表id
        }
        PageHelper.startPage(page, pageSize);
        //and学历--转成证书名称
        //TODO 根据学历名称转成学历证书名称
        String certificate_name = "";
        List<PersonManageModel> personManageModelList = personalInfoDao.selectPersonByCombination(company.trim(), salaryStart.trim(), salaryEnd.trim(), certificate_name.trim(), name.trim(), gradeId.trim());

        return new PageInfo<>(personManageModelList);
    }

    /**
     * 把薪资范围转成段-徐玲博-2018-1-3 16:05:16
     *
     * @param salaryRange 薪资范围
     * @return 段列表
     */
    public List<String> salaryRangeSegment(String salaryRange) {
        List<String> stringList = new ArrayList<>();
        //salaryRange切开，分成薪资Start~薪资End

        String salaryStart = "";
        String salaryEnd = "";
        stringList.add(salaryStart);
        stringList.add(salaryEnd);
        return stringList;
    }

    /**
     * 模糊查询（姓名or性别or期数） - 李爽-2017-12-7 17:36:52
     *
     * @param queryParam 模糊查询条件
     * @return 毕业生list
     */
    @Override
    public List<PersonalInfoEntity> selectPersonByNameSexGrade(String queryParam) {
        if (StringUtils.isEmpty(queryParam)) {
            return null;
        }
        //去字典表中模糊查询期数，取得字典表id和期数
        List<DictionaryEntity> dictionaryEntities = dictionaryService.selectIdsByNameGrade(queryParam);
        List<String> gradeList = new ArrayList<>();
        //把字典表id放到list中供查询用
        if (CollectionUtils.isNotEmpty(dictionaryEntities)) {
            for (DictionaryEntity dictionaryEntitie : dictionaryEntities) {
                String id = dictionaryEntitie.getId();
                gradeList.add(id);
            }
        }
        PersonalInfoExample personalInfoWhereConditions = new PersonalInfoExample();
        personalInfoWhereConditions.or().andNameLike(queryParam);
        personalInfoWhereConditions.or().andSexLike(queryParam);
        if (CollectionUtils.isNotEmpty(gradeList)) {
            personalInfoWhereConditions.or().andGradeIn(gradeList);
        }
        personalInfoWhereConditions.createCriteria()
                .andIsDeleteEqualTo((byte) 0);
        List<PersonalInfoEntity> personalInfoEntityList = personalInfoDao.selectByExample(personalInfoWhereConditions);
        if (CollectionUtils.isNotEmpty(personalInfoEntityList)) {
            //把期数id替换成期数、或者给期数id增加期数
            for (PersonalInfoEntity personalInfoEntity : personalInfoEntityList) {
                String id = personalInfoEntity.getGrade();
                for (DictionaryEntity dictionaryEntity : dictionaryEntities) {
                    String did = dictionaryEntity.getId();
                    if (StringUtils.equals(id, did)) {
                        personalInfoEntity.setGrade(dictionaryEntity.getDictName());
                        break;
                    }
                }
            }
            return personalInfoEntityList;
        }
        return null;
    }


    /**
     * 通知-查询毕业生信息-徐玲博-2017-12-6 11:55:36
     *
     * @return 毕业生信息列表
     */
    @Override
    public List<PersonGradeModel> selectPersonInfo() {
        List<PersonalInfoEntity> personalInfoEntityList = personalInfoDao.selectPersonInfo();
        List<PersonGradeModel> personGradeModelList = new ArrayList<>();
        for (PersonalInfoEntity personalInfoEntity : personalInfoEntityList) {
            PersonGradeModel personGradeModel = new PersonGradeModel();
            String gradeName = dictionaryService.findDictionaryNameById(personalInfoEntity.getGrade());

            personGradeModel.setGradeName(gradeName);
            BeanUtils.copyProperties(personalInfoEntity, personGradeModel);
            personGradeModelList.add(personGradeModel);
        }
        return personGradeModelList;
    }

    /**
     * 分页查询-根据地域类型、地域、期数、姓名、性别，查询学员信息-李爽-2018-1-13 17:27:42
     *
     * @return 学员信息
     */
    @Override
    public PageInfo<PersonInfoModel> selectPersonInfoByRegionGradeNameSex(PersonInfoParamsModel personInfoParamsModel, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);//分页查询
        List<PersonInfoModel> personInfoModelList = personalInfoDao.selectPersonInfoByRegionGradeNameSex(personInfoParamsModel);
        return new PageInfo<>(personInfoModelList);
    }

    /**
     * 查询所有期数及对应期数人员 郑晓东 2018年1月14日18点30分
     *
     * @return
     */
    @Override
    public List<PeriodPersonModel> findPeriodPersonModels() {
        return personalInfoDao.findPeriodPersonModels();
    }

    /**
     * 数据中心-添加在校生或毕业生信息列表到到Personal表中-徐玲博-2018-1-15 15:02:09
     *
     * @param personalInfoEntityList 个人信息实体
     * @return 受影响行
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addListToPersonal(List<PersonGradeModel> personalInfoEntityList) {
        int flag;
        int graduateFlag = 0;
        int studentFlag = 0;

        String isNotGraduate = IS_NOT_GRADUATE;//是否毕业 0/1 否/是
        List<PersonalInfoEntity> graduateList = new ArrayList<>();//毕业生列表
        List<StudentEntity> studentEntityList = new ArrayList<>();//在校生列表
        //1、list中有字段is_graduate标识是否毕业，筛选放进不同的list中
        //  查询这些信息，是否已经在Person表中存在，如果存在则不放进下面的list中
        for (PersonGradeModel personGradeModel : personalInfoEntityList) {
            PersonalInfoEntity personalInfoEntity = new PersonalInfoEntity();

            //通过登录账号查看是否有重复上传的学生
            String loginId = personGradeModel.getLoginId();
            PersonalInfoEntity singlePersonInfo = personalInfoDao.selectPersonByLoginId(loginId);

            //期数名称改成id
            String gradeName = personGradeModel.getGradeName();
            String grade = dictionaryService.findDictionaryIdByName(gradeName);
            personalInfoEntity.setGrade(grade);
            personalInfoEntity.setId(BaseUuidUtils.base58Uuid());//新建id
            personalInfoEntity.setLoginId(personGradeModel.getLoginId());
            personalInfoEntity.setName(personGradeModel.getName());
            personalInfoEntity.setWechat(personGradeModel.getWechat());
            personalInfoEntity.setQq(personGradeModel.getQq());
            personalInfoEntity.setEmail(personGradeModel.getEmail());

            // 如果查询到的数据为空，表示没有该学生的信息
            if (singlePersonInfo == null) {
                //判断是否毕业，0未毕业，1已经毕业
                if (isNotGraduate.equals(personGradeModel.getIsGraduateName())) {
                    //在校生列表
                    StudentEntity studentEntity = new StudentEntity();
                    studentEntity.setCode(personalInfoEntity.getLoginId());//学号
                    studentEntityList.add(studentEntity);
                } else {
                    //毕业生列表
                    personalInfoEntity.setIsGraduate(1);
                    graduateList.add(personalInfoEntity);
                }
            } else {
                //如果查询该学生已存在信息，且他是在校生，则更新他的信息
                if (isNotGraduate.equals(personGradeModel.getIsGraduateName())) {
                    //在校生列表,更新
                    StudentEntity studentEntity = new StudentEntity();
                    studentEntity.setCode(personalInfoEntity.getLoginId());//学号
                    studentEntity.setUpdateTime(singlePersonInfo.getUpdateTime());//修改的时间戳
                    studentEntityList.add(studentEntity);
                }
            }
        }
        //2、毕业生有信息，添加到personal表中
        if (CollectionUtils.isNotEmpty(graduateList)) {
            graduateFlag = insertPersonInfoList(graduateList);//添加毕业生信息到personInfo 表
            /**
             * 调用权限的接口-田晓冰-2018年3月11日15:35:21
             */
            //region 添加权限中
            List<AllusersEntity> allUsersEntitiesList = new ArrayList<>();
            for (PersonalInfoEntity personalInfoEntity : graduateList) {
                AllusersEntity allUsersEntity = new AllusersEntity();
                allUsersEntity.setUserCode(personalInfoEntity.getPhone());
                allUsersEntity.setPassword(personalInfoEntity.getPhone());
                allUsersEntity.setUserName(personalInfoEntity.getPhone());
                allUsersEntity.setId(personalInfoEntity.getId());
                allUsersEntity.setEmail(personalInfoEntity.getEmail());
                allUsersEntity.setTelNum(personalInfoEntity.getPhone());
                allUsersEntity.setSchoolNo("666888");
                allUsersEntity.setIsLock(0);
                allUsersEntitiesList.add(allUsersEntity);
            }
            List<String> userIDs = new ArrayList<>();
            allUsersEntitiesList.forEach(m -> userIDs.add(m.getId()));
            boolean flagAu = allusersFacade.insertUserList(allUsersEntitiesList);
            if (flagAu) {
                //根据角色查询角色id
                String roleId = queryRoledId("一般用户", "23VAJAVAXT492QKFsfUBru");
                if (roleId != null) {
                    //绑定用户和角色
                    insertUserRole(userIDs, roleId);
                }
            }
            //endregion
        }
        //3、在校生有信息，调用基础的querySynData（）方法，返回学员详细信息，并添加到Personal表中
        if (CollectionUtils.isNotEmpty(studentEntityList)) {
            //保存在校生信息到人员信息表中
            studentFlag = insertStudentToPerson(studentEntityList);
        }
        flag = graduateFlag + studentFlag;
        return flag;
    }

    /**
     * 批量添加人员信息-徐玲博-2018-1-25 15:13:49
     *
     * @param personalInfoEntityList 人员信息表
     * @return 受影响行
     */
    @Override
    public int insertPersonInfoList(List<PersonalInfoEntity> personalInfoEntityList) {
        return personalInfoDao.insertAll(personalInfoEntityList);
    }


    /**
     * 数据中心-定时同步数据中心-徐玲博-2018-1-15 14:11:28
     *
     * @return 受影响行
     */
    @Override
    public int synchronizeDataWarehouse() {
        int flag;
        //查询出所有在校生信息
        List<PersonalInfoEntity> personalInfoEntityList = personalInfoDao.selectAllStudent();
        //在校生列表
        //定时调用基础的querySynData（）方法，参数学号和update_time
        List<StudentEntity> studentEntityList = setStudentParam(personalInfoEntityList);

        //更新返回的学员信息到Person表中
        flag = insertStudentToPerson(studentEntityList);
        return flag;//受影响行
    }

    /**
     * 从人员表中获得字段设置学生参数--徐玲博-2018-1-27 10:53:00
     *
     * @param personalInfoEntityList 人员列表
     * @return 学生列表
     */
    @Override
    public List<StudentEntity> setStudentParam(List<PersonalInfoEntity> personalInfoEntityList) {

        //在校生列表
        List<StudentEntity> studentEntityList = new ArrayList<>();
        for (PersonalInfoEntity p : personalInfoEntityList) {
            StudentEntity studentEntity = new StudentEntity();
            studentEntity.setCode(p.getLoginId());//学号
            studentEntity.setUpdateTime(p.getUpdateTime());//更新时间戳
            studentEntityList.add(studentEntity);
        }
        return studentEntityList;
    }

    /**
     * 查询到的学生信息保存在人员表中-徐玲博-2018-1-27 11:13:14
     *
     * @param studentEntityList 学生列表
     * @return 受影响行
     */
    @Override
    public int insertStudentToPerson(List<StudentEntity> studentEntityList) {
        int studentFlag;
        //根据在校生信息，从基础获得在校生信息
        List<StudentEntity> backStudentList = new ArrayList<>();
        //TODO 调用基础系统，查询在校生信息
        // backStudentList=querySynData(studentEntityList);
        //将返回的学生信息放进人员列表中
        List<PersonalInfoEntity> personInfoList = new ArrayList<>();
        for (StudentEntity studentEntity : backStudentList) {
            PersonalInfoEntity personalInfoEntity = new PersonalInfoEntity();
            personalInfoEntity.setLoginId(studentEntity.getId());//学号
            personalInfoEntity.setName(studentEntity.getName());//姓名
            personalInfoEntity.setSex(studentEntity.getSex());//性别
            personalInfoEntity.setEnterCollegeTime(studentEntity.getEntranceDate());//入学时间
            personalInfoEntity.setNativePlace(studentEntity.getNativePlacenativePlace());//籍贯
            personalInfoEntity.setEmail(studentEntity.getEmail());//邮箱
            personalInfoEntity.setWechat(studentEntity.getOpenId());//微信
            personInfoList.add(personalInfoEntity);
                /*基础信息比互助网信息多的字段*/
            //身份证号
            //照片
            //民族
            //户口所在地
//                personalInfoEntity.setBirthday(studentEntity.getBirthday);//出生年月
        }
        studentFlag = insertPersonInfoList(personInfoList);//保存在校生信息到人员信息表中
        return studentFlag;
    }

    /**
     * 地域接口-组合查询人员地域信息-徐玲博-2018-1-31 16:52:28
     *
     * @param name       个人名称
     * @param sex        性别
     * @param regionName 地域 省市县
     * @param grade      期数
     * @return 个人地域列表
     */
    @Override
    public List<PersonReginModel> selectPersonRegion(String name, String sex, String regionName, String grade, String dictionaryAddressId) {
        List<PersonReginModel> personReginModelList = personalInfoDao.selectPersonRegion(name.trim(), sex.trim(), regionName.trim(), grade.trim(), dictionaryAddressId.trim());
        //TODO 需要优化 同一个人查询一次期数
        for (PersonReginModel personReginModel : personReginModelList) {
            //年级返回字符串
            String gradeid = personReginModel.getGrade();
            String gradeName = dictionaryService.findDictionaryNameById(gradeid);
            personReginModel.setGradeName(gradeName);
        }
        return personReginModelList;
    }

    /**
     * 毕业生-根据毕业生 用户Id-修改个人信息-徐玲博-2017-11-19 11:28:07
     *
     * @param personInfoModel 用户实体
     * @return 受影响行
     */
    @Override
    public int updatePersonInfo(PersonInfoModel personInfoModel) {
        int flag;
        PersonalInfoEntity pie = new PersonalInfoEntity();
        String userId = personInfoModel.getId();
        pie.setAddress(personInfoModel.getAddress());
        pie.setBirthday(personInfoModel.getBirthday());
        pie.setEmail(personInfoModel.getEmail());
        pie.setEmergName(personInfoModel.getEmergName());
        pie.setEmergPhone(personInfoModel.getEmergPhone());
        pie.setEmergRelation(personInfoModel.getEmergRelation());
        pie.setEnterCollegeTime(personInfoModel.getEnterCollegeTime());
        pie.setEnglishName(personInfoModel.getEnglishName());
        pie.setEnterDmtTime(personInfoModel.getEnterDmtTime());
        pie.setGrade(personInfoModel.getGrade());
        pie.setGraduateCollegeTime(personInfoModel.getGraduateCollegeTime());
        pie.setGraduateDmtTime(personInfoModel.getGraduateDmtTime());
        pie.setLoginId(personInfoModel.getLoginId());
        pie.setName(personInfoModel.getName());
        pie.setNativePlace(personInfoModel.getNativePlace());
        pie.setOperatorId(personInfoModel.getOperatorId());
        pie.setPhone(personInfoModel.getPhone());
        pie.setProfessionalField(personInfoModel.getProfessionalField());
        pie.setSex(personInfoModel.getSex());
        pie.setQq(personInfoModel.getQq());
        pie.setWechat(personInfoModel.getWechat());
        pie.setId(userId);
        pie.setRemark(personInfoModel.getRemark());
        pie.setRegionId(personInfoModel.getRegionId());
        pie.setIsGraduate(personInfoModel.getIsGraduate());
        pie.setNativeRegionId(personInfoModel.getNativeRegionId());
        pie.setIsDelete(personInfoModel.getIsDelete());
        //保存个人信息
        flag = this.updateById(pie);
        //保存个人头像路径
        String pictureUrl = personInfoModel.getPictureUrl();

        int flag2 = pictureService.addPicture(pictureUrl, userId);//保存图片路径
        return flag + flag2;
    }
//---------注册----------------------------------------------------------------------------

    /**
     * 用户添加（注册）-袁甜梦-2018年3月11日11:26:28
     *
     * @param userModel
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertUser(UserModel userModel) {
        boolean flag = false;
        //1、判断注册的用户是否存在
        PersonalInfoEntity personalInfoEntity = personalInfoDao.selectPersonByLoginId(userModel.getUserCode());
        //2、不存在，添加到权限user表和本服务person_info表
        if (personalInfoEntity == null) {
            PersonalInfoEntity personalInfoEntity1 = new PersonalInfoEntity();
            //添加用户名和用户真实姓名到person_info表
            personalInfoEntity1.setId(BaseUuidUtils.base58Uuid());
            personalInfoEntity1.setLoginId(userModel.getUserCode());
            personalInfoEntity1.setName(userModel.getUserRealName());
            int count = personalInfoDao.insert(personalInfoEntity1);

            if (count > 0) {
                List<AllusersEntity> list = new ArrayList<>();
                AllusersEntity allusersEntity = new AllusersEntity();
                allusersEntity.setUserCode(userModel.getUserCode());
                allusersEntity.setUserName(userModel.getUserRealName());
                allusersEntity.setId(personalInfoEntity1.getId());
                allusersEntity.setPassword(userModel.getPassword());
                allusersEntity.setSchoolNo("666888");
                allusersEntity.setIsLock(0);
                list.add(allusersEntity);
                flag = allusersFacade.insertUserList(list);
            }
            if (flag) {
                //根据角色查询角色id
                String roleId = queryRoledId("一般用户", "23VAJAVAXT492QKFsfUBru");
                if (roleId != null) {
                    //绑定用户和角色
                    List<String> userList = new ArrayList<>();
                    userList.add(personalInfoEntity1.getId());
                    flag = insertUserRole(userList, roleId);
                }
            }
        }
        return flag;
    }

    /**
     * 调用权限根据角色查询角色id-袁甜梦-2018年3月12日08:55:31
     *
     * @param roleName  角色名称 一般用户（目前默认）、管理员
     * @param companyId 23VAJAVAXT492QKFsfUBru （固定）
     * @return
     */
    public String queryRoledId(String roleName, String companyId) {
        return roleFacade.queryRoleId(roleName, companyId);
    }

    /**
     * 调用权限绑定用户和角色-袁甜梦-2018年3月12日09:17:21
     *
     * @param userList 用户list
     * @param roleId   角色id
     * @return boolean
     */
    public boolean insertUserRole(List<String> userList, String roleId) {
        return userRoleFacade.insertUserRole(userList, roleId);
    }

    /**
     * addToAuth-调用权限接口-田晓冰-2018年3月11日16:24:32
     *
     * @param personalInfoEntity 个人信息实体
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addToAuth(PersonalInfoEntity personalInfoEntity) {
        //region 调用权限接口-田晓冰-2018年3月11日16:24:32
        AllusersEntity allUsersEntity = new AllusersEntity();
        allUsersEntity.setUserCode(personalInfoEntity.getPhone());
        allUsersEntity.setId(personalInfoEntity.getId());
        allUsersEntity.setPassword(personalInfoEntity.getPhone());
        allUsersEntity.setUserName(personalInfoEntity.getPhone());
        allUsersEntity.setEmail(personalInfoEntity.getEmail());
        allUsersEntity.setTelNum(personalInfoEntity.getPhone());
        allUsersEntity.setSchoolNo("666888");
        allUsersEntity.setIsLock(0);
        List<AllusersEntity> allList = new ArrayList<>();
        allList.add(allUsersEntity);
        boolean flag = allusersFacade.insertUserList(allList);
        if (flag) {
            //根据角色查询角色id
            String roleId = queryRoledId("一般用户", "23VAJAVAXT492QKFsfUBru");
            if (roleId != null) {
                //绑定用户和角色
                List<String> userList = new ArrayList<>();
                userList.add(allUsersEntity.getId());
                flag = insertUserRole(userList, roleId);
            }
        }
        return flag;
        //endregion
    }

    //region addPersonInfo-管理员端添加用户-田晓冰-2018年3月15日
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addPersonInfo(PersonalInfoEntity personalInfoEntity) {
        //1、判断注册的用户是否存在(loginID字段存的是他的手机号）
        PersonalInfoEntity person = personalInfoDao.selectPersonByLoginId(personalInfoEntity.getPhone());
        //如果用户已存在
        if (person != null) {
            return -1;
        }
        personalInfoEntity.setLoginId(personalInfoEntity.getPhone());
        int flag = personalInfoDao.insert(personalInfoEntity);
        this.addToAuth(personalInfoEntity);
        return flag;
    }
    //endregion

    /**
     * 修改密码-袁甜梦-2018年3月20日09:20:37
     *
     * @param userId   用户id
     * @param userCode 用户code
     * @param password 密码
     * @return
     */
    @Override
    public boolean updateUserPassword(String userId, String userCode, String password) {
      boolean flag=  allusersFacade.updateUserPassword(userId, userCode, password);
        return false;
    }

    /**
     * 个人重置密码-袁甜梦-2018年3月20日14:07:18
     * @param userCode 用户编码
     * @return 是否更新成功
     */
    @Override
    public boolean resetPassword(String userCode) {
        String schoolNo="666888";
         boolean flag = allusersFacade.resetPassword(schoolNo, userCode);
        return flag;
    }

}
